<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/statistics' }"
        >账单统计</el-breadcrumb-item
      >
      <el-breadcrumb-item>生活开支</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="16">
        <el-col :span="6">
          <el-input
            placeholder="请输入搜索的账单"
            v-model="queryInfo.query"
            clearable
            @clear="getBills"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getBills"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加生活开支</el-button
          >
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchBillType"
            placeholder="请选择"
            @change="getMoneyOfMonthByBillType"
          >
            <el-option
              v-for="item in billTypeList"
              :key="item.billTypeCode"
              :label="item.billTypeName"
              :value="item.billTypeCode"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="2"
          ><span class="billTypeMoneyClass"
            >{{ this.billTypeMoney }}元</span
          ></el-col
        >
      </el-row>

      <el-row :gutter="20" class="secondElRow">
        <el-col :span="12">
          <span>本月总消费：{{ this.totalBillMoneyOfMonth }}元 </span>
        </el-col>
      </el-row>

      <el-divider></el-divider>

      <!-- 用户列表区域 -->
      <el-table
        :data="billList"
        border
        stripe
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="内容"
          prop="content"
          width="100px"
        ></el-table-column>
        <el-table-column
          label="账单类型"
          prop="billType"
          width="100px"
          :formatter="billTypeFormatter"
        ></el-table-column>
        <el-table-column label="金额" prop="money"></el-table-column>
        <el-table-column label="消费时间" prop="costTime"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>

        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeBillById(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="->,total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加账单的对话框 -->
    <el-dialog
      title="添加账单"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-divider></el-divider>
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="formRules"
        ref="addFormRef"
        label-width="100px"
        size="mini"
      >
        <el-form-item label="消费" prop="content">
          <el-input
            v-model="addForm.content"
            placeholder="请输入消费内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="账单类型" prop="billType">
          <el-select
            v-model="addForm.billType"
            placeholder="请选择"
            @change="billTypeChange"
            filterable
          >
            <el-option
              v-for="item in billTypeList"
              :key="item.billTypeCode"
              :label="item.billTypeName"
              :value="item.billTypeCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input
            v-model="addForm.money"
            placeholder="请输入消费余额"
          ></el-input>
        </el-form-item>
        <el-form-item label="消费时间" required>
          <el-col :span="10">
            <el-form-item prop="costTime"
              ><el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="addForm.costTime"
                style="width: 120%"
                editable
                value-format="yyyy-MM-dd"
              ></el-date-picker
            ></el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addBill">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 更新账单的对话框 -->
    <el-dialog
      title="更新账单"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-divider></el-divider>
      <!-- 内容主体区域 -->
      <el-form
        :model="editForm"
        :rules="formRules"
        ref="editFormRef"
        label-width="80px"
        size="mini"
      >
        <el-form-item label="消费" prop="content">
          <el-input
            v-model="editForm.content"
            placeholder="请输入消费内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="账单类型" prop="billType">
          <el-select
            v-model="editForm.billType"
            placeholder="请选择"
            filterable
          >
            <el-option
              v-for="item in billTypeList"
              :key="item.billTypeCode"
              :label="item.billTypeName"
              :value="item.billTypeCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input
            v-model="editForm.money"
            placeholder="请输入消费余额"
          ></el-input>
        </el-form-item>
        <el-form-item label="消费时间" required>
          <el-col :span="10">
            <el-form-item prop="costTime"
              ><el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="editForm.costTime"
                style="width: 120%"
                editable
                value-format="yyyy-MM-dd"
              ></el-date-picker
            ></el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editBill">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      total: 0,
      queryInfo: {
        query: '',
        userId: window.sessionStorage.getItem('token'),
        // 当前的页数
        pageNum: 1,
        // 当前每页显示多少条数据
        pageSize: 10,
        startTime: '',
        endTime: ''
      },
      billList: [],
      billType: '',
      searchBillType: '',
      totalBillMoneyOfMonth: 0,
      billTypeList: [],
      billTypeMoney: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      editDialogVisible: false,
      // 添加基金的表单数据
      addForm: {
        userId: window.sessionStorage.getItem('token'),
        content: '',
        billType: '',
        money: '',
        costTime: ''
      },
      // 添加表单的验证规则对象
      formRules: {
        content: [
          { required: true, message: '请输入消费内容', trigger: 'blur' }
        ],
        money: [{ required: true, message: '请输入消费金额', trigger: 'blur' }],
        costTime: [
          {
            required: true,
            message: '请输入消费时间',
            type: 'string',
            trigger: 'blur'
          }
        ]
      },
      editForm: {
        id: '',
        userId: window.sessionStorage.getItem('token'),
        content: '',
        billType: '',
        money: '',
        costTime: ''
      }
    }
  },
  created() {
    this.getBills()
    this.getBillTypes()
    this.getMonthBillMoney()
  },
  methods: {
    // 获取所有的金额
    async getBills() {
      const { data: res } = await this.$http.get('/bill', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.code !== 1) {
        return this.$message.error('获取所有生活开支失败！')
      }
      this.billList = res.data.pageList
      this.total = res.data.total
    },

    async getBillTypes() {
      const { data: res } = await this.$http.get('/bill/getBillTypes')
      if (res.code !== 1) {
        return this.$message.error('获取本月总消费失败！')
      }
      this.billTypeList = res.data
      console.log(this.billTypeList)
    },

    async getMonthBillMoney() {
      const userId = window.sessionStorage.getItem('token')
      const { data: res } = await this.$http.get(
        '/bill/getMonthBillMoney/' + userId
      )
      if (res.code !== 1) {
        return this.$message.error('获取本月总消费失败！')
      }
      this.totalBillMoneyOfMonth = res.data
    },
    async getMoneyOfMonthByBillType(billType) {
      console.log(billType)
      const userId = window.sessionStorage.getItem('token')
      const { data: res } = await this.$http.get(
        '/bill/getMoneyOfMonthByBillType?billTypeCode=' +
          billType +
          '&userId=' +
          userId
      )
      if (res.code !== 1) {
        return this.$message.error('获取本月消费类型失败！')
      }
      this.billTypeMoney = res.data
    },

    async showEditDialog(id) {
      const { data: res } = await this.$http.get('/bill/getBillById/' + id)

      if (res.code !== 1) {
        return this.$message.error('查询账单失败！')
      }

      this.editForm = res.data
      this.editDialogVisible = true
    },

    addBill() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.warning('必填项不能为空')
          return
        }

        console.log(this.addForm)
        const { data: res } = await this.$http.post('bill', this.addForm)

        if (res.code !== 1) {
          return this.$message.error('添加账单失败！')
        }

        this.$message.success('添加账单成功！')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        this.$refs.addFormRef.resetFields()
        // 重新获取用户列表数据
        this.getBills()
      })
    },

    editBill() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.warning('必填项不能为空')
          return
        }

        const { data: res } = await this.$http.put('/bill', this.editForm)

        if (res.code !== 1) {
          this.$message.error('更新账单失败！')
        }

        this.$message.success('更新账单成功！')
        // 隐藏添加用户的对话框
        this.editDialogVisible = false
        this.$refs.editFormRef.resetFields()
        // 重新获取用户列表数据
        this.getBills()
      })
    },

    async removeBillById(id) {
      const { data: res } = await this.$http.delete('/bill', {
        params: { ids: id }
      })
      if (res.code !== 1) {
        return this.$message.error('删除账单失败！')
      }
      this.$message.success('删除账单成功！')
      this.getBills()
    },

    billTypeChange(row) {
      console.log(row)
    },

    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    billTypeFormatter(row, column) {
      if (row.billType === 1) {
        return '正餐'
      } else if (row.billType === 2) {
        return '在外吃饭'
      } else if (row.billType === 3) {
        return '多多买菜'
      } else if (row.billType === 4) {
        return '美团优选'
      } else if (row.billType === 5) {
        return '淘菜菜'
      } else if (row.billType === 6) {
        return '盒马集市'
      } else if (row.billType === 7) {
        return '零食'
      } else if (row.billType === 8) {
        return '车费'
      } else if (row.billType === 9) {
        return '房租'
      } else if (row.billType === 10) {
        return '旅游'
      } else if (row.billType === 11) {
        return '红包'
      } else if (row.billType === 12) {
        return '父母'
      } else if (row.billType === 13) {
        return '小荷包'
      } else {
        return '其他'
      }
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getBills()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pageNum = newPage
      this.getBills()
    }
  }
}
</script>

<style lang="less" scoped>
.secondElRow {
  margin-top: 15px;
  font-size: 12px;
  font-weight: 700;
}
.el-divider {
  margin-top: 8px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.el-col-4 {
  width: 17%;
}
.el-form .el-form-item .el-input {
  width: 195px;
}

.el-form {
  margin-left: 100px;
}
/deep/.el-dialog .el-dialog__footer {
  text-align: center;
  margin-top: -25px;
}
.el-dialog .el-divider {
  margin-top: -25px;
}
.billTypeMoneyClass {
  line-height: 40px;
}
</style>
